# -*- coding:utf-8 -*-
from datetime import datetime
from flask import url_for
from flask_sqlalchemy import SQLAlchemy
from flask_login import UserMixin

db = SQLAlchemy()


class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), nullable=False)
    api_key = db.Column(db.String(64), unique=True, index=True)


class Questions(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(64), index=True)
    descriptions = db.Column(db.Text, nullable=False)
    user = db.relationship('User', backref=db.backref('questions', lazy='dynamic'))
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    createTime = db.Column(db.DateTime, default=datetime.now)

    @property
    def url(self):
        return url_for('get_q', id=self.id)


class Answers(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    content = db.Column(db.Text, nullable=False)
    questions = db.relationship('Questions', backref=db.backref('answers', lazy='dynamic'))
    questions_id = db.Column(db.Integer, db.ForeignKey('questions.id'))
    user = db.relationship('User', backref=db.backref('Answers', lazy='dynamic'))
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    createTime = db.Column(db.DateTime, default=datetime.now)

    def __repr__(self):
        return '<Answers %r>' % self.id
